package com.sntra.beibi.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sntra.beibi.common.DotUtils;
import com.sntra.beibi.domain.LearnPage;
import com.sntra.beibi.domain.Page;
import com.sntra.beibi.request.Article;
import com.sntra.beibi.service.BookService;
import com.sntra.beibi.service.LearnPageService;


@RestController
@Controller
public class PageController {
    
    @Value("${doc.rootdir}")
	private String dir;
    
    @Value("${img.rootdir}")
	private String imgDir;
    
    @Value("${domain.name}")
	private String domainName;
    
    @Autowired
	private LearnPageService lpService;
    
    @Autowired
   	private BookService bookService;
    
    @RequestMapping(value = "/dot/read", method = RequestMethod.GET)
    @ResponseBody
    public Article read(HttpServletRequest request ,Model model) {
    	String ids = request.getParameter("identify");
    	String[] ida = ids.split("/");
    	Article art = new Article();
    	if(ida!=null && ida.length==2) {
    		Integer lbId = Integer.parseInt(ida[0]);
    		Integer pn = Integer.parseInt(ida[1]);
    		LearnPage lp = new LearnPage();
    		lp.setLearnBookId(lbId);
    		lp.setPageNo(pn);
	        lp = lpService.selectPage(lp);
	        if(lp!=null) {
	        	art.setId(lp.getPageNo());
		        if( StringUtils.hasText(lp.getImgUrl())) {
		        	art.setContent(domainName + lp.getImgUrl());
		        } 
	        }
    	}
        return art;
    }
    
    @RequestMapping(value = "/read/view", method = RequestMethod.GET)
    @ResponseBody
    public Article view(HttpServletRequest request,Model model) {
    	String ids = request.getParameter("identify");
    	String[] ida = ids.split("/");
    	Article art = new Article();
    	if(ida!=null && ida.length==2) {
    		Integer lbId = Integer.parseInt(ida[0]);
    		Integer pn = Integer.parseInt(ida[1]);
    		Page lp = new Page();
    		lp.setBookId(lbId);
    		lp.setPageNo(pn);
	        lp = bookService.selectPage(lp);
	        if(lp!=null) {
	        	art.setId(lp.getPageNo());
		        if( StringUtils.hasText(lp.getImgUrl())) {
		        	art.setContent(domainName + lp.getImgUrl());
		        } 
	        }
    	}
        return art;
    }

    @RequestMapping(value = "/pdf/download", method = RequestMethod.GET)
    @ResponseBody
    public String downloadPdf( HttpServletResponse response ,Model model) {
        //待下载文件名
        String fileName = "sntra.pdf";
        //设置为pdf格式的文件
        response.setHeader("content-type", "application/pdf");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[2048];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
        	LearnPage lp = lpService.selectLatestPage();
        	if(lp!=null && StringUtils.hasText(lp.getUrl())) {
	            outputStream = response.getOutputStream();
	            //这个路径为待下载文件的路径
	            bis = new BufferedInputStream(new FileInputStream(new File(lp.getUrl())));
	            int read = bis.read(buff);
	            //通过while循环写入到指定了的文件夹中
	            while (read != -1) {
	                outputStream.write(buff, 0, buff.length);
	                outputStream.flush();
	                read = bis.read(buff);
	            }
        	}
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                	outputStream.flush();
                    outputStream.close();
                    response.flushBuffer();
                    response.setStatus(200);
                    return "OK";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "ERROR";
    }
    
    @RequestMapping(value = "/bg/download", method = RequestMethod.GET)
    @ResponseBody
    public String downloadBg(HttpServletRequest req, HttpServletResponse response ,Model model) {
    	Integer bookID = Integer.parseInt(req.getParameter("bookId").trim());
    	Integer pageID = Integer.parseInt(req.getParameter("pageId").trim());
          
        //待下载文件名
        String fileName = bookID+"_"+pageID+".png";
        //设置为png格式的文件
        response.setHeader("content-type", "image/png");
        response.setContentType("image/png");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] buff = new byte[2048];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
        	Page page = new Page();
        	page.setBookId(bookID);
        	page.setPageNo(pageID);
        	Page p = bookService.selectPage(page);
        	if(p!=null && StringUtils.hasText(p.getImgUrl())) {
	            outputStream = response.getOutputStream();
	            //这个路径为待下载文件的路径
	            bis = new BufferedInputStream(new FileInputStream(new File(p.getImgUrl())));
	            int read = bis.read(buff);
	            //通过while循环写入到指定了的文件夹中
	            while (read != -1) {
	                outputStream.write(buff, 0, buff.length);
	                outputStream.flush();
	                read = bis.read(buff);
	            }
        	}
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                	outputStream.flush();
                    outputStream.close();
                    response.flushBuffer();
                    response.setStatus(200);
                    return "OK";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "ERROR";
    }
   
}

